<template>
  <div class="time-clock" :style="{ color: timeColor, fontSize: timeSize + 'px', fontWeight: timeBold ? 'bold' : 'normal' }">
    {{ formattedTime }}
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { ComponentInstance } from '@/types/visual-app';

const props = defineProps<ComponentInstance>()

// 默认参数
const timeFormat = ref('HH:mm:ss')
const timeColor = ref('#409EFF')
const timeSize = ref(32)
const timeBold = ref(false)

// 监听 props.config.attributes.props 变化
watch(
  () => props.config?.attributes?.props,
  (val) => {
    if (val) {
      timeFormat.value = val.format || 'HH:mm:ss'
      timeColor.value = val.color || '#409EFF'
      timeSize.value = val.size || 32
      timeBold.value = !!val.bold
    }
  },
  { immediate: true, deep: true }
)

const now = ref(new Date())
let timer: number | null = null

function pad(n: number) {
  return n < 10 ? '0' + n : n
}

const formattedTime = computed(() => {
  const d = now.value
  const y = d.getFullYear()
  const m = pad(d.getMonth() + 1)
  const day = pad(d.getDate())
  const h = pad(d.getHours())
  const min = pad(d.getMinutes())
  const s = pad(d.getSeconds())
  // 简单格式化
  return timeFormat.value
    .replace('YYYY', String(y))
    .replace('MM', String(m))
    .replace('DD', String(day))
    .replace('HH', String(h))
    .replace('mm', String(min))
    .replace('ss', String(s))
})

onMounted(() => {
  timer = window.setInterval(() => {
    now.value = new Date()
  }, 1000)
})

onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
})
</script>

<style scoped>
.time-clock {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  letter-spacing: 2px;
  user-select: none;
}
</style> 